﻿module StyleSheets

open Utils
open System
open CssTypes
open CssParser
open DefaultCss
open CssExpander


let readStyle src = toStyleSpec (parseDeclarations src)

let readRules css = 
    let (Statements(imports, stmts)) = parseStyleSheet css
    let rules = stmts |> List.choose (function 
                                        | Ruleset(rule) -> Some rule
                                        | _ -> None)
    [for (Rule(selectors, declarations)) in rules 
            -> Rule1(selectors,(toStyleSpec declarations))]


let applyRules (matcher:Selector->bool)  (style:StyleSpec) (rules : Rule1 list) =
    let rec applyRules1 (style:StyleSpec) (rules : Rule1 list) =
        match rules with
        | [] -> style
        | (Rule1(selectors,decls))::rest ->
            if List.exists matcher selectors
            then
                let style = style.join(decls)
                applyRules1 style rest
            else
                applyRules1 style rest
    applyRules1 style rules

let getCascadedStyle (rules:Rule1 list) (matcher:Selector->bool) =
    applyRules matcher (StyleSpec(Map.empty)) rules


(* mutable collection of style rules *)
type StylesheetSet() =
    let mutable _rules = readRules defaultCss
    member this.rules with get() = _rules
    member this.addCss cssText =
        let rules = readRules cssText
        do _rules <- _rules @ rules


